<template>
  <div id='app'>
    <header class="app-header">
      <xy-header></xy-header>
    </header>
    <div class="app-body">
      <div class="app-left" v-show="menuShow">
        <xy-menu></xy-menu>
      </div>
      <div class="app-right" :style="menuShow?'':'min-width: 1200px;'">
        <!-- tabs -->
        <!-- <div class="app-right-tabs">
          <div class="app-right-tabs-container">
            <el-tabs v-model="tabsSelect" type="card" @tab-remove="tabsRemove" @tab-click="tabsClick">
              <el-tab-pane v-for="(item,index) in tabs" :key="item.name" :label="item.title" :name="item.name" :closable="index != 0">
              </el-tab-pane>
            </el-tabs>
          </div>
          <div class="app-right-tabs-operator">
            <i @click="tabsPrev" class="operator-btn icon-arrows-left"></i>
            <i @click="tabsNext" class="operator-btn icon-arrows-right"></i>
            <el-dropdown trigger="click">
              <span class="el-dropdown-link">
                <i class="operator-btn icon-scrappy-more"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="toCurrTabs()">定位到当前窗口</el-dropdown-item>
                <el-dropdown-item @click.native="closeTabs('all')">关闭所有窗口</el-dropdown-item>
                <el-dropdown-item @click.native="closeTabs('other')">关闭其他窗口</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div> -->
        <div class="app-right-content">
          <div class="app-right-view">
            <keep-alive :include="include">
              <router-view v-if="$route.meta.keepAlive && isRouterAlive"></router-view>
            </keep-alive>
            <router-view v-if="!$route.meta.keepAlive && isRouterAlive"></router-view>
          </div>
        </div>

      </div>
    </div>

    <el-dialog :title="dialog.title" :visible.sync="dialog.show" :width="dialog.width" :close-on-click-modal="false">
      <span v-html="dialog.content"></span>
      <span slot="footer" class="dialog-footer">

        <el-button size="small" :type="item.type" v-for="(item,index) in dialog.btns" :key="index" @click="item.callback">{{item.text}}</el-button>
      </span>
    </el-dialog>

    <object id="globalMainView" type="application/x-eloamplugin" width="256" height="256" name="view"></object>
    <object id="globalThumbView" type="application/x-eloamplugin" width="150" height="150" name="thumb"></object>

    <div class="app-fixed">

    </div>
  </div>
</template>
<script>
  import '@SCSS/common.scss'
  import xyHeader from '@C/xyHeader'
  import xyMenu from '@C/xyMenu'


  export default {
    provide() {
      return {
        reload: this.reload
      }
    },
    data: function () {
      return {
        tabsSelect: '/index',
        tabs: [
        {
          component: ['index'],
          title: '首页',
          name: '/index',
          content: '/index',
          query: {}
        }],
        include: ['index'],
        dialog: {
          show: false,
          width: "30%",
          title: "提示",
          content: "",
          btns: [
          {
            text: "",
            type: "",
            callback: ""
          }]
        },
        isRouterAlive: true,
        menuShow: true // 是否显示右侧菜单
      }
    },
    components: {
      xyHeader,
      xyMenu
    },
    methods: {
      reload() {
        this.isRouterAlive = false
        this.$nextTick(() => (this.isRouterAlive = true))
      },

      toCurrTabs() {
        var index = 0;
        for (let i = 0; i < this.tabs.length; i++) {
          if (this.tabs[i].name == this.tabsSelect) {
            index = i;
            break;
          }
        }
        var x = index * 120 + 20;

        var el = document.querySelector(".app-right-tabs .el-tabs__nav");
        var nav = document.querySelector(".app-right-tabs .el-tabs__nav-scroll");

        console.log(x, el.clientWidth, nav.clientWidth);
        if (x <= nav.clientWidth) {
          x = 0;
        }

        if (x != 0) {
          x -= 360;
        }

        el.style.transform = "translateX(" + (-x) + "px)";

      },
      closeTabs(type,noJump) {
        if (type == 'other') {
          var currentTab = null;

          this.tabs.forEach((tab, index) => {
            if (this.tabsSelect == tab.name) {
              currentTab = tab;
              return true;
            }
            if (index != 0) {
              tab.component.forEach(name => {
                this.removeKeepAlive(name);
              });

            }
          });
          if (!currentTab) return;
          if (currentTab == this.tabs[0]) {
            this.tabs = [this.tabs[0]];
          } else {
            this.tabs = [this.tabs[0], currentTab];
          }
        } else if (type == 'all') {

          for (var i = 1; i < this.tabs.length; i++) {
            this.tabs[i].component.forEach(name => {
              this.removeKeepAlive(name);
            });
          }

          this.tabs = [this.tabs[0]];

          if (this.tabsSelect != this.tabs[0].name) {
            this.tabsSelect = this.tabs[0].name;
            this.$toPage(this.tabs[0].content, this.tabs[0].query);
          }
        } else if(type == 'current'){
          if(this.tabsSelect == "/" || this.tabsSelect == "/index" || this.tabsSelect == "/index.html"){
            return;
          }
          this.tabsRemove(this.tabsSelect,noJump);
          return;
        }
        var el = document.querySelector(".app-right-tabs .el-tabs__nav");
        el.style.transform = "translateX(0px)";
      },
      tabsClick(tab) {
        var activeTab = null;
        this.tabs.forEach(item => {
          if (item.name == tab.name) {
            activeTab = item;
          }
        });
        if (!activeTab) return;
        this.$toPage(activeTab.content, activeTab.query);
      },

      tabsRemove(tabsName,noJump) {
        let tabs = this.tabs;
        let activeName = this.tabsSelect;

        let next = true;
        if (activeName === tabsName) {
          tabs.forEach((tab, index) => {
            if (tab.name === tabsName) {
              var targetComponse = this.$route.matched[0] && this.$route.matched[0].instances.default;
              if(targetComponse && targetComponse.beforeCloseView){
                next = false;
                targetComponse.beforeCloseView(()=>{
                  this.tabsRemoveNext(tabsName,noJump);
                });
              }
            }
          });
        }
        if(next){
          this.tabsRemoveNext(tabsName,noJump);
        }
      },
      tabsRemoveNext(tabsName,noJump){
        let tabs = this.tabs;
        let activeName = this.tabsSelect;
        let activeTab = null;

        tabs.forEach((tab, index) => {
          if (tab.name === tabsName) {
            tab.component.forEach(name => {
              this.removeKeepAlive(name);
            });
          }
        });

        if (activeName === tabsName) {
          tabs.forEach((tab, index) => {
            if (tab.name === tabsName) {
              let nextTab = tabs[index + 1] || tabs[index - 1];
              if (nextTab) {
                activeName = nextTab.name;
                if(!noJump){
                  this.$toPage(nextTab.content, nextTab.query);
                }
              }
            }
          });
        }

        this.tabsSelect = activeName;
        this.tabs = tabs.filter(tab => tab.name !== tabsName);
      },

      removeKeepAlive(name) {
        if (!name) return;
        var index = this.include.indexOf(name);
        if (index != -1) {
          this.include.splice(index, 1);
        }
      },
      addKeepAlive(name) {
        if (!name) return;
        var index = this.include.indexOf(name);
        if (index == -1) {
          this.include.push(name);
        }
      },
      getParentPath(r, parentPath) {
        parentPath = r.meta.parent || parentPath;
        if (!r.meta.parent) {
          return parentPath;
        }
        for (let i = 0; i < this.$router.options.routes.length; i++) {
          let item = this.$router.options.routes[i];
          if (item.path == parentPath) {
            return this.getParentPath(item, parentPath);
          }
        }
        return parentPath;
      },
      createTabs(route) {
        var self = this;

        //现在的组件
        var targetComponse = this.$route.matched[0] && this.$route.matched[0].instances.default;
        var oComponse = this.$route.matched[0] && this.$route.matched[0].components.default;

        if (!route.name || !route.path) return;
        var existed = false;
        route = {
          name: route.name,
          path: route.path,
          meta: route.meta || {},
          query: JSON.parse(JSON.stringify(route.query))
        };
        //if (route.path == '/') route.path = '/index';
        if (route.path == '/') route.path = this.tabs[0].name;

        //获取最原始的路由
        var parentPath = this.getParentPath(route);
        var path = route.path;
        this.tabs.forEach(tab => {
          if (path == tab.name || parentPath == tab.name) {
            existed = true;
            tab.query = route.query;
            if (tab.content != path) {
              tab.content = path;
              if (!parentPath) {
                //如果不是父组件
              }
              tab.component.push(oComponse.name);
            }
          }

        });

        this.tabsSelect = parentPath || path;

        this.addKeepAlive(oComponse.name);
        if (!existed) {
          var name = route.name;
          if (parentPath) {
            //获取父亲路由的名字
            this.$router.options.routes.forEach(r => {
              if (r.path == parentPath) {
                name = r.name;
              }
            });
          }
          this.tabs.push({
            component: [oComponse.name],
            title: name,
            name: parentPath || path,
            content: path,
            query: route.query
          });
          targetComponse && targetComponse.reset && targetComponse.reset();
        }
      },
      tabsPrev() {
        var el = document.querySelector(".app-right-tabs .el-tabs__nav");
        var x = el.style.transform || "";
        x = x.replace(/translateX\((.*?)px\)/im, "$1");
        x = Number(x);
        if (isNaN(x)) x = 0;
        x = x + 160;
        if (x > 0) x = 0;
        el.style.transform = "translateX(" + x + "px)";
      },
      tabsNext() {
        var el = document.querySelector(".app-right-tabs .el-tabs__nav");
        var nav = document.querySelector(".app-right-tabs .el-tabs__nav-scroll");

        if (el.clientWidth > nav.clientWidth) {
          var x = el.style.transform || "";

          x = x.replace(/translateX\((.*?)px\)/im, "$1");
          x = Number(x);
          if (isNaN(x)) x = 0;
          x = x - 160;
          if (-x > el.clientWidth - nav.clientWidth) x = nav.clientWidth - el.clientWidth - 40;
          el.style.transform = "translateX(" + x + "px)";
        }
      },
      resize() {
        var content = document.querySelector(".app-right-content");
        if (content) {
          document.querySelector(".app-right-view").style.minHeight = (content.offsetHeight - 40) + "px";
        }
      }
    },
    created: function () {
      var self = this;

      document.querySelector('body').addEventListener("click", function () {
        self.$root.eventHandle.$emit('BODY_CLICK');
      }, false);

      var interval = setInterval(() => {
        var route = self.$route;
        if (route.name) {
          clearInterval(interval);
          this.createTabs(route);
        }
      }, 100);

      this.$root.eventHandle.$on("KEEP_ALIVE_ADD", (name) => {
        this.include.push(name);
      });

      this.$root.eventHandle.$on("KEEP_ALIVE_DELETE", (name) => {
        this.removeKeepAlive(name);
      });

      this.$root.eventHandle.$on("RESET_TABS", () => {
        this.closeTabs('all');
      });

      this.$root.eventHandle.$on("ALERT", (opts) => {
        opts = opts || {};
        this.dialog = {
          show: true,
          width: opts.width || "30%",
          title: opts.title || "警告",
          content: opts.content || "",
          btns: [
          {
            text: opts.confirmText || "确 定",
            type: "primary",
            callback: function () {
              if (opts.callback) {
                var result = opts.callback();
                if (result !== false) {
                  self.dialog.show = false;
                }
              } else {
                self.dialog.show = false;
              }
            }
          }]
        };
      });

      this.$root.eventHandle.$on("CONFIRM", (opts) => {
        opts = opts || {};
        opts.btns = opts.btns || [];
        for (let i = 0; i < opts.btns.length; i++) {
          ! function () {
            var cb = opts.btns[i].callback;
            opts.btns[i].callback = function () {
              var result = cb && cb();
              if (result !== false) {
                self.dialog.show = false;
              }
            };
          }();
        }
        this.dialog = {
          show: true,
          width: opts.width || "30%",
          title: opts.title || "提示",
          content: opts.content || "",
          btns: opts.btns
        };
      });

      this.$root.eventHandle.$on("HIDE_DIALOG", () => {
        this.dialog.show = false;
      });

      this.$root.eventHandle.$on("CLOSE_CURRENT_TAB", (noJump) => {
        this.closeTabs("current",noJump);
      });
      
      this.$root.eventHandle.$on("UPDATE_SUB_MENU_INDEX", (flag) => {
        if(!flag){
          this.menuShow = false
        }else{
          this.menuShow = true
        }
        this.$forceUpdate()
      });

      window.onresize = function () {
        self.$root.eventHandle.$emit("RESIZE");
        self.resize();
      }
    },
    mounted() {
      this.resize();
      //解决v-tip字体模糊
      setInterval(()=>{
        var doms = document.querySelectorAll(".v-tip-container");
        for(let i=0;i<doms.length;i++){
          var dom = doms[i];
          if(dom.style.display == 'none'){
            continue;
          }
          var transform = dom.style.transform;
          if(!transform) continue;
          var m = transform.match(/(\d+(\.\d+)?)px/g);
          if(m){
            for(let j=0;j<m.length;j++){
              transform = transform.replace(m[j],Math.ceil(m[j].replace("px",""))+"px");
            }
          }
          dom.style.transform = transform;

        }
      },100);
      this.$root.eventHandle.$emit("UPDATE_USERTYPE")
      // this.$postStream('/admin/instance/ccb/polyv/authUser/getUserInfo.do',{
      //   data:{},
      //   success:(res)=>{
      //     if(res.success){
      //       sessionStorage.setItem("curAccountAppId", res.object.appId)
      //       sessionStorage.setItem("curAccountEmail", res.object.email)
      //       sessionStorage.setItem("userType", res.object.userType)
      //       //userType:1为频道管理员，2为应用管理员，3为平台管理员 4为超级管理员
      //       this.$root.eventHandle.$emit("UPDATE_USERTYPE")
      //     }else{
      //       this.$message.error('系统内部错误，请联系管理员')
      //     }
      //   },
      //   error:()=>{
      //     this.$message.error('系统内部错误，请联系管理员')
      //   }
      // })
    },
    watch: {
      '$route': function (to, from) {
        this.createTabs(to);
        this.$root.eventHandle.$emit("UPDATE_SUB_MENU_SHOW")
        this.$root.eventHandle.$emit("UPDATE_MENU")
      }
    },
    destroyed() {}
  }
</script>

<style lang="scss" scoped>
  @import '../../assets/scss/variable.scss';
  @import '../../assets/scss/mixin.scss';
  #app {
    height: 100%;
    display: -webkit-box;
    /* autoprefixer: off */
    -webkit-box-orient: vertical;
    /* autoprefixer: on */
  }

  .app-header {
    display: -webkit-box;
    height: 60px;
    width: 100%;
    min-width: 1200px;
  }

  .app-body {
    display: -webkit-box;
    -webkit-box-flex: 1;
    height: 100%;
    width: 100%;
  }

  .app-left {
    display: -webkit-box;
    width: 200px;
  }

  .app-right {
    display: -webkit-box;
    -webkit-box-flex: 1;
    -webkit-box-orient: vertical;
    width: 100%;
    min-width: 1000px;
    background-color: $xy-border-color-light;
  }

  .app-right-tabs {
    height: 50px;
    width: 100%;
    background-color: #FFF;
    display: flex;
    & .app-right-tabs-operator {
      background-color: #FFF;
      height: 50px;
      font-size: 0;
      flex: 0 0 auto;
      width: 150px;
      border-bottom: 1px solid #E4E7ED;
      & i {
        box-shadow: none !important;
      }
      & .el-dropdown-link {
        box-shadow: none !important;
      }
      & .operator-btn {
        width: 50px;
        height: 50px;
        line-height: 50px;
        text-align: center;
        border-left: 1px solid $xy-border-color-base;
        color: $xy-text-color-placeholder;
        font-size: 20px;
        vertical-align: top;
        cursor: pointer;
        &:hover{
          color: $xy-color-main!important;
        }
      }
    }
    & .app-right-tabs-container {
      height: 50px;
      flex: 1 1 auto;
      width: 1%;
    }
  }

  .app-right-content {
    -webkit-box-flex: 1;
    width: 100%;
    overflow: auto;
    padding: 20px;
    @include scroll();
  }

  .app-right-view {
    width: 100%;
    background-color: #fff;
    min-height: 100%;
  }

  #globalMainView,
  #globalThumbView {
    position: fixed;
    z-index: 9999;
    top: -1000px;
    left: -1000px;
  }

  .app-right-fullscreen {
    min-width: auto;
  }
</style>
